package com.ftar.urgent.ui;

import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ftar.urgent.R;
import com.ftar.urgent.api.resp.ItemRecordsVo;
import com.ftar.urgent.constant.ArouterConstant;
import com.ftar.urgent.databinding.ActivityCaptureBinding;
import com.ftar.urgent.http.model.PictureJsonBean;
import com.ftar.urgent.viewmodel.CaptureModel;
import com.ftar.urgent.viewmodel.CommonEvent;
import com.ftar.urgent.viewmodel.SP_Constants;
import com.ftar.urgent.voice.OffLineVoiceCmd;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author: wei.jin
 * @date: 2023/7/3
 * @email: wei.jin@fanttec.com
 * @description：
 */
@Route(path = ArouterConstant.CAPTURE_ACTIVITY)
public class CaptureActivity extends BaseActivity {
    private String TAG = this.getClass().getSimpleName();
    private ActivityCaptureBinding mBinding;
    private CaptureModel mCaptureModel;

    private SoundPool soundPool;
    private int soundId;

    @Autowired
    public int currentId;
    @Autowired
    public int currentCode;
    @Autowired
    public int parentId;
    @Autowired
    public int parentCode;

    /**
     * 页面
     * 1：拍照识别
     * 2：语音识别
     */
    @Autowired
    public int pageType;

    @Override
    protected ViewDataBinding getChildBinding() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_capture, null, false);
        mBinding.setHandler(this);
        return mBinding;
    }

    @Override
    protected String voiceHint() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        mBinding.setLifecycleOwner(this);
        init();
    }

    private void init() {
        mCaptureModel = new CaptureModel(this, mBinding);
        if (pageType == 2) {
            mCaptureModel.setStep(CaptureModel.STEP_VOICE_INDEX);
        } else {
            mCaptureModel.setStep(CaptureModel.STEP_IDLE);
        }
        observe();
        tipsVoiceInit();
    }

    private void tipsVoiceInit() {
        SoundPool.Builder spb = new SoundPool.Builder();
        spb.setMaxStreams(10);
        soundPool = spb.build();
        soundId = soundPool.load(this, R.raw.tips, 1);
    }

    /**
     * Observe data changed, observe it and do something
     */
    private void observe() {
        /**
         * Data From picture
         */
        mCaptureModel.pictureData.observe(mBinding.getLifecycleOwner(), new Observer<PictureJsonBean>() {
            @Override
            public void onChanged(PictureJsonBean pictureJsonBeans) {
                if (pageType == 2) {
                    if (pictureJsonBeans == null) {
                        mCaptureModel.setStep(CaptureModel.STEP_VOICE_REG_FAILED);
                    } else if (pictureJsonBeans.getType().equals("UnRecognized") || pictureJsonBeans.getType().equals("未识别")) {
                        mBinding.voiceResultText.setText("未识别");
                        mBinding.resultTitle.setText("未识别");
                        mCaptureModel.setStep(CaptureModel.STEP_VOICE_REG_FAILED);
                    } else {
                        mCaptureModel.setStep(CaptureModel.STEP_VOICE_REG);
                        mBinding.resultTitle.setText(pictureJsonBeans.getType());
                        mBinding.voiceResultText.setText(pictureJsonBeans.getType());
                    }
                } else {
                    if (pictureJsonBeans == null) {
                        mCaptureModel.setStep(CaptureModel.STEP_PICTURE_REG_FAILED);
                    } else if (pictureJsonBeans.getType().equals("UnRecognized") || pictureJsonBeans.getType().equals("未识别")) {
                        mBinding.resultTitle.setText("未识别");
                        mCaptureModel.setStep(CaptureModel.STEP_PICTURE_REG_FAILED);
                    } else {
                        mCaptureModel.setStep(CaptureModel.STEP_PICTURE_REG);
                        PictureJsonBean mapPicture = mCaptureModel.mapCustomSize(pictureJsonBeans);
                        mBinding.resultTitle.setText(mapPicture.getType());
                        mCaptureModel.sendToAnXin(pictureJsonBeans.getType());
                    }
                }

            }
        });

        /**
         * Data from An XIN
         */
        mCaptureModel.anXinData.observe(mBinding.getLifecycleOwner(), new Observer<List<ItemRecordsVo>>() {
            @Override
            public void onChanged(List<ItemRecordsVo> vo) {
                Log.d(TAG, "observe anxin update:");
                if (vo != null && vo.size() > 0) {
                    mCaptureModel.setStep(mCaptureModel.STEP_SUCCESS);
                    soundPool.play(soundId, 1, 1, 0, 0, 1);
                } else {
                    mCaptureModel.setStep(mCaptureModel.STEP_SUCCESS_RESULT_EMPTY);
                }


            }
        });
    }

    private void handleOfflineWords(String words) {
        switch (words) {
            // 一键拍照
            case OffLineVoiceCmd.OfflineVoice.CAPTURE_TAKE_PHOTO:
                mCaptureModel.takePhoto();
                break;
            // 发起监测
            case OffLineVoiceCmd.OfflineVoice.CAPTURE_THINGS_SEND:
                if (mCaptureModel.getStep() == CaptureModel.STEP_VOICE_REG) {
                    // 语音识别结果后，发起检测
                    String result = mBinding.voiceResultText.getText().toString();
                    mCaptureModel.sendToAnXin(result);
                } else {
                    mCaptureModel.sendPhoto();
                }
                break;
            // 一键重拍
            case OffLineVoiceCmd.OfflineVoice.CAPTURE_RE_TAKE_PHOTO:
                mBinding.resultTitle.setText("");
                mBinding.commandTakePicture.setVisibility(View.VISIBLE);
                mBinding.commandReTakePicture.setVisibility(View.GONE);
                mCaptureModel.reTakPhoto();
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_BACK:
                if (mCaptureModel.getStep() == CaptureModel.STEP_IDLE
                        || mCaptureModel.getStep() == CaptureModel.STEP_PICTURE
                        || mCaptureModel.getStep() == CaptureModel.STEP_PICTURE_REG_FAILED) {
                    // 从拍照 返回
                    backPage();
                } else if (mCaptureModel.getStep() == CaptureModel.STEP_SUCCESS_MORE) {
                    // 从更多页面 返回
                    mCaptureModel.setStep(CaptureModel.STEP_SUCCESS);
                } else if (mCaptureModel.getStep() == CaptureModel.STEP_VOICE_INDEX
                        || mCaptureModel.getStep() == CaptureModel.STEP_VOICE_REG
                        || mCaptureModel.getStep() == CaptureModel.STEP_VOICE_REG_FAILED) {
                    // 从语音主页 返回
                    mCaptureModel.stopOnLineAsr();
                    backPage();
                }
                break;
            case OffLineVoiceCmd.OfflineVoice.CAPTURE_RECORD_AUDIO:
                mCaptureModel.startOnlineAsr();
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_MORE:
                mCaptureModel.setStep(CaptureModel.STEP_SUCCESS_MORE);
                mBinding.resultTitle.setVisibility(View.GONE);
                mBinding.resultTableLy.setVisibility(View.GONE);
                mBinding.resultMoreLy.setVisibility(View.GONE);
                mBinding.resultPageLy.setVisibility(View.GONE);
                mBinding.resultMoreDetailView.setVisibility(View.VISIBLE);
                mBinding.commandBack.setVisibility(View.VISIBLE);
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_PRE:
                //上一页
                mCaptureModel.goPreviousPage();
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_PAGE_NEXT:
                //下一页
                mCaptureModel.goNextPage();
                break;
            case OffLineVoiceCmd.OfflineVoice.GLOBAL_END:
            case OffLineVoiceCmd.OfflineVoice.CHECK_END:
                backPage();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (mCaptureModel.getStep() == CaptureModel.STEP_SUCCESS) {
                    mCaptureModel.goPreviousPage();
                }
                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (mCaptureModel.getStep() == CaptureModel.STEP_SUCCESS) {
                    mCaptureModel.goNextPage();
                }
                break;
            case KeyEvent.KEYCODE_F9:
                if (mCaptureModel.getStep() == CaptureModel.STEP_SUCCESS) {
                    mCaptureModel.setStep(CaptureModel.STEP_SUCCESS_MORE);
                } else if (mCaptureModel.getStep() == CaptureModel.STEP_SUCCESS_MORE) {
                    mCaptureModel.setStep(CaptureModel.STEP_SUCCESS);
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            onKeyDown(event.getKeyCode(), event);
        }
        return false;
    }

    private void backPage() {
        this.finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommonEvent(CommonEvent event) {
        if(!event.getmClass().equals(this.getClass().getName())){
            return;
        }
        switch (event.getMsg()) {
            case SP_Constants.EVENT_COMMAND_ASR:
                String keyWord = event.getData();
                handleOfflineWords(keyWord);
                Log.d(TAG, "offline:" + keyWord);
                break;
        }
    }
}
